<?php

class UsersController extends FrontEndController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','upload','cabinet','settings','sendMessage','indexMessage','inMessage','outMessage','viewMessage','myObjects',
					'booking','allBooking','newBooking','oldBooking',
					'trips', 'allTrips', 'oldTrips'
				),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		// если запрос асинхронный
        if(Yii::app()->request->isAjaxRequest){
			$comment = new UsersComments;
			$comment->text			=	Yii::app()->request->getPost('textComment');
	        $comment->profile_id	=	Yii::app()->request->getPost('profile_id');
	        $comment->user_id		=	Yii::app()->user->id;
	        $comment->crdate		=	date("Y-m-d H:i:s");
	        $comment->save();

	        $comments = UsersComments::model()->findAll(
	        	'profile_id=:profile_id',
	        	array(':profile_id'=>$comment->profile_id)
	        );
	        $this->renderPartial('_commentsList', array('comments'=>$comments));
            Yii::app()->end();
        }
        else
        {
			$model = Users::model()->findByPk($id);
			$this->render('view',array(
				'model'		=>	$model,
				'bookmarks'	=>	$model->bookmarks,
				'comments'	=>	$model->comments,
			));
        }
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Users;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Users']))
		{
			$model->attributes=$_POST['Users'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate()
	{
		$id = Yii::app()->user->id;
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Users']))
		{
			$model->attributes=$_POST['Users'];
			$model->oldPassword=$_POST['Users']['oldPassword'];		

			// Змінити пароль
			if($model->oldPassword != NULL) {
				$model->oldPassword = Users::model ()->ganaratePassword($model->oldPassword);
				if( $model->validate('oldPassword') ) {
					if( $model->validate('confirmPassword')  ) {
						$model->password = Users::model ()->ganaratePassword($model->newPassword);
					}
				}
			}
			// Змінити Email
			if($model->oldEmail != NULL) {
				if($model->validate('oldEmail')) {
					if($model->newEmail != NULL && $model->validate('newEmail'))
						$model->email = $model->newEmail;
				}
			}
			if($model->save())
				$this->redirect(array('cabinet','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Users');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Users('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Users']))
			$model->attributes=$_GET['Users'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	public function actionCabinet()
	{
		// если запрос асинхронный
        if(Yii::app()->request->isAjaxRequest){
			$comment = new UsersComments;
			$comment->text			=	Yii::app()->request->getPost('textComment');
	        $comment->profile_id	=	Yii::app()->request->getPost('profile_id');
	        $comment->user_id		=	Yii::app()->user->id;
	        $comment->crdate		=	date("Y-m-d H:i:s");
	        $comment->save();

	        $comments = UsersComments::model()->findAll(
	        	'profile_id=:profile_id',
	        	array(':profile_id'=>$comment->profile_id)
	        );
	        $this->renderPartial('_commentsList', array('comments'=>$comments));
            Yii::app()->end();
        }
        else
        {
        	$id = Yii::app()->user->id;
			$model = Users::model()->findByPk($id);
			$this->render('cabinet',array(
				'model'		=>	$model,
				'bookmarks'	=>	$model->bookmarks,
				'comments'	=>	$model->comments,
			));
        }
	}

	public function actionSettings($id)
	{
		if($id == Yii::app()->user->id) 
		{
			$model=$this->loadModel($id);
			if(isset($_POST['Users']))
			{
				$model->attributes=$_POST['Users'];
				if($model->save())
					$this->redirect(array('cabinet','id'=>$model->id));
			}

			$this->render('_settings',array(
				'model'=>$model,
			));
		}
		else
        	$this->redirect(array('view','id'=>$id));
	}
	public function actionUpload()
	{
		$id = Yii::app()->user->id;
		$model=$this->loadModel($id);
		if(isset($_POST['Users']))
		{
			$path = $_SERVER['DOCUMENT_ROOT'].'/upload/images/';
			$fileName = self::saveImage($model->avatar, $model, $path);
			Yii::app()->user->setState('avatar', $fileName);
			$model->avatar=$fileName;
			if($model->save())
				Yii::app()->user->setFlash('success', Yii::t('main', 'Your avatar successfully changed!'));
				$this->refresh();
		}

		$this->render('upload',array(
			'model'=>$model,
		));
	}
	public function actionSendMessage($id)
	{
		$model = new UsersMessages;
		if(isset($_POST['UsersMessages']))
		{
			$model->attributes=$_POST['UsersMessages'];
			$model->from_id = Yii::app()->user->id;
			$model->to_id = $id;
			$model->crdate = date("Y-m-d H:i:s");;
			if($model->save())
				$this->redirect(array('view','id'=>$id));
		}

		$this->render('_sendMessage',array(
			'model'=>$model,
		));
	}
	public function actionIndexMessage()
	{	

		$dataProvider = UsersMessages::getDialogs();
		$this->render('_indexMessage',array(
			'dataProvider'=>$dataProvider,
		));
	}
	
	public function actionViewMessage($companion,$show = NULL)
	{
		// если запрос асинхронный
		
        if(Yii::app()->request->isAjaxRequest){
			$message = new UsersMessages;
			$message->text			=	Yii::app()->request->getPost('textMessage');
	        $message->to_id			=	Yii::app()->request->getPost('to_id');
	        $message->from_id		=	Yii::app()->user->id;
	        $message->crdate		=	date("Y-m-d H:i:s");
	        $message->save();

	        $messages = UsersMessages::model()->findAll(
				array(
					'order'=> 'crdate ASC',
					'condition'=>'(`from_id`=:user_1 AND `to_id`=:user_2 AND `remove_to` = 0) OR (`from_id`=:user_2 AND `to_id`=:user_1 AND `remove_from` = 0)',
					'params'=>array(':user_1'=>$message->to_id, ':user_2'=>Yii::app()->user->id)
				)
			);
	        $this->renderPartial('_messagesList', array(
	        	'messages'	=>	$messages,
	        	'countMessages' => count($messages),
	        ));
            Yii::app()->end();
        }
        else
        {
			$messages = UsersMessages::model()->findAll(
				array(
					'order'=> 'crdate ASC',
					'condition'=>'(`from_id`=:user_1 AND `to_id`=:user_2 AND `remove_to` = 0) OR (`from_id`=:user_2 AND `to_id`=:user_1 AND `remove_from` = 0)',
					'params'=>array(':user_1'=>$companion, ':user_2'=>Yii::app()->user->id),
				)
			);
			$companion_info = Users::model()->findByPk($companion,array(
				'select'=>'id, full_name, avatar',
			));
			$this->render('_viewMessage',array(
				'messages'		=>	$messages,
				'companion_info'=>	$companion_info,
				'countMessages' => count($messages),
			));
        }
	}

	public function actionMyObjects()
	{
		$id = Yii::app()->user->id;
   		$dataProvider = Object::model()->findAll(
   			'user_id=:user_id',
   			array(':user_id'=>$id)
   		);
        $this->render('my_objects',array(
			'dataProvider'	=>	$dataProvider,
			// 'user'			=>	$model->user,
		));
	}

	public function actionBooking($id)
	{
		$object = Object::model()->findByPk($id);
		$bookings = Booked::model()->findAll(array(
			'condition'=>'object_id=:object_id AND status=0',
			'params'=>array(':object_id'=>$id),
			'order'=>'crdate DESC',
		));
		$this->render('booking', array(
			'object'=>$object,
			'bookings'=>$bookings,
		));
	}
	public function actionNewBooking($id)
	{
		$bookings = Booked::model()->findAll(array(
			'condition'=>'object_id=:object_id AND status=0',
			'params'=>array(':object_id'=>$id),
			'order'=>'crdate DESC',
		));
		$this->renderPartial('_bookingList', array('bookings'=>$bookings));
	}
	public function actionOldBooking($id)
	{
		$bookings = Booked::model()->findAll(array(
			'condition'=>'object_id=:object_id AND status NOT IN (0)',
			'params'=>array(':object_id'=>$id),
			'order'=>'crdate DESC',
		));
		$this->renderPartial('_bookingList', array('bookings'=>$bookings));
	}
	public function actionAllBooking($id = 1)
	{
		$bookings = Booked::model()->findAll(array(
			'condition'=>'object_id=:object_id',
			'params'=>array(':object_id'=>$id),
			'order'=>'crdate DESC',
		));
		$this->renderPartial('_bookingList', array('bookings'=>$bookings));
	}

	public function actionTrips()
	{
		$model = Booked::model()->findAll(array(
			'condition'=>'user_id=:user_id AND check_out>=NOW("Y-m-d")',
			'params'=>array(':user_id'=>Yii::app()->user->id),
			'order'=>'check_in',
		));
		if(Yii::app()->request->isAjaxRequest)
		{
			$this->renderPartial('_tripsList',array('model'=>$model));
		}
		else
			$this->render('trips',array('model'=>$model));
	}
	public function actionAllTrips()
	{
		$model = Booked::model()->findAll(array(
			'condition'=>'user_id=:user_id',
			'params'=>array(':user_id'=>Yii::app()->user->id),
			'order'=>'check_in DESC',
		));
		$this->renderPartial('_tripsList',array('model'=>$model));
	}
	public function actionOldTrips()
	{
		$model = Booked::model()->findAll(array(
			'condition'=>'user_id=:user_id AND check_out<=NOW("Y-m-d")',
			'params'=>array(':user_id'=>Yii::app()->user->id),
			'order'=>'check_in DESC',
		));
		$this->renderPartial('_tripsList',array('model'=>$model));
	}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Users::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='users-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
